package cn.yy.cloudpay;

import java.util.ArrayList;
import java.util.List;
import cn.yy.cloudpay.activity.PayActivity;
import cn.yy.cloudpay.application.CloudPayApplication;
import cn.yy.cloudpay.cardread.FeixiScanT2Activity;
import cn.yy.cloudpay.db.RecordDB;
import cn.yy.cloudpay.db.RecordModel;
import cn.yy.cloudpay.scan.FeixiScanActivity;
//import cn.yy.cloudpay.scan.FeixiScanT2Activity;
import cn.yy.cloudpay.scan.FeixiScanTActivity;
import cn.yy.cloudpay.scan.ScanCodeActivity;
import cn.yy.cloudpay.usb.DeviceListActivity;
import cn.yy.cloudpay.util.Constant;
import cn.yy.cloudpay.util.StringUtil;
import cn.yy.cloudpay.util.ThirdTransType;
import cn.yy.cloudpay.view.ToastUtil;
import cn.yy.cloudpay.scan.YimaScanActivity;
import cn.yy.pos.launcher.service.Payway;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends PayActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		CloudPayApplication.from = 0;
		CloudPayApplication.deviceSN = mApplication.getDeviceSN();
		//同步未返回的交易
		orderix = 0;
		initBankDB();
		initData();
	}

	public void initData(){
		gridview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
				selPayType(arg2,null);
			}
		});

		//云收单类型
		if("2".equals(isFromType)){
			payType = getIntent().getStringExtra("payType");//1 支付宝 2 微信 3 银联 4 凭条 5 翼支付 6 QQ钱包 success 百度钱包 8 京东钱包 9 榕城通 10 苏宁易付宝
			if(!StringUtil.isEmpty(payType)){
				selPay();
			}
		}
	}

	/**
	 * 云收单支付
	 */
	public void selPay(){
		String alipay = getPayCloud();
		if(StringUtil.isEmpty(alipay)){
			return;
		}
		ArrayList<Payway> payways = mApplication.getOperator().getPayways();
		for(Payway payway:payways){
			if(alipay.indexOf(payway.getPaywaynum()+",")!=-1){
				selPayType(0,payway);
				return;
			}
		}
	}

	private void selPayType(int arg,Payway payway){
		if(payway==null){
			ArrayList<Payway> payways = mApplication.getOperator().getPayways();
			payway = payways.get(arg);
		}
		pay_1(payway);
		yinshen(payway);
		nongshang(payway);
		other(payway);
		lianhui(payway);
        wft(payway);
	}


	/**　==============================================================
	 * 原生支付
	 * @param payway
	 */
	private void pay_1(Payway payway){
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_ALIPAY)){
			mPayType = Constant.PAY_TYPE_ALIPAY;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			pay_2();
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_MICROPAY)){
			mPayType = Constant.PAY_TYPE_MICROPAY;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			pay_2();
		}
	}
	//键盘输入
	public void pay_2() {
		if(!StringUtil.isEmpty(totalMoney)){
			initIntent();
			showScanCode();
		}else{
			showKeyboard(Constant.GREQUEST_CODE_KEYBOARD, true); // 键盘输入
		}
	}
	//==============================================================
//====================银盛支付==========================================
	private void yinshen(Payway payway){

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_ALIPAY_YS)){
			mPayType = Constant.PAY_TYPE_ALIPAY_YS;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			if(!StringUtil.isEmpty(totalMoney)){
				Intent intent = initIntent();
				callPay(intent, 2006);
			}else{
				callPay(new Intent(), ThirdTransType.TRANS_NULL);
			}
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_MICROPAY_YS)){
			mPayType = Constant.PAY_TYPE_MICROPAY_YS;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			if(!StringUtil.isEmpty(totalMoney)){
				Intent intent = initIntent();
				callPay(intent, 2004);
			}else{
				callPay(new Intent(), ThirdTransType.TRANS_NULL);
			}
		}

		//银联支付
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_BANKUNION)){
			mPayType = Constant.PAY_TYPE_BANKUNION_YS;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			if(!StringUtil.isEmpty(totalMoney)){
				Intent intent = initIntent();
				callPay(intent, 1016);
			}else{
				callPay(new Intent(), ThirdTransType.TRANS_NULL);
			}
		}

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_BANKCANCEL_YS)){
			mPayType = Constant.PAY_TYPE_BANKCARD;
			mOpType = Constant.KEYBOARD_OP_TYPE_RETURN;
			callPay(new Intent(), 106);
		}

		//银盛
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_BANKCARD)){
			bankPayType = Constant.BANKPAYTYPE_YINGSHEN;
			mPayType = Constant.PAY_TYPE_BANKCARD;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			consume_ys();
		}
		//银盛秒到
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_BANKCARD_Q)){
			bankPayType = Constant.BANKPAYTYPE_YINGSHEN;
			mPayType = Constant.PAY_TYPE_BANKCARD_Q;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			consumeQ_ys();
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_SETTING_YS)){
			mApplication.getOperator().setBankType(Constant.BANKPAYTYPE_YINGSHEN);
			settings();
		}

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_PREAUTH_YS)){
			mApplication.getOperator().setBankType(Constant.BANKPAYTYPE_YINGSHEN);
			preauth();
		}
	}

	// 预授权
	public void preauth(){
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, CardPreauthActivity.class);
		startActivity(intent);
	}

	private void callPay(Intent intent, int transType) {
		if(transType == ThirdTransType.TRANS_NULL){
			showKeyboard(Constant.GREQUEST_CODE_SCANNIN_YS, true);
		}else {
			intent.setAction("com.ys.smartpos.pay.sdk");
			intent.putExtra("transType", transType);
			startActivityForResult(intent, Integer.valueOf("100" + transType));
		}
	}
	//刷卡消费
	public void consume_ys() {
		if(!StringUtil.isEmpty(totalMoney)){
			Intent intent = initIntent();
			callPay(intent, 101);
		}else {
			showKeyboard(Constant.GREQUEST_CODE_CARDPAY, false);
		}
	}

	public void consumeQ_ys() {
		if(!StringUtil.isEmpty(totalMoney)){
			Intent intent = initIntent();
			callPay(intent, 1009);
		}else {
			showKeyboard(Constant.GREQUEST_CODE_CARDPAY, false);
		}
	}

	//====================银盛支付==========================================
//====================农商支付==========================================
	private void nongshang(Payway payway){
		//农商
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_ALIPAY_NS)){
			mPayType = Constant.PAY_TYPE_ALIPAY_NS;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			if(!StringUtil.isEmpty(totalMoney)){
				Intent intent = initIntent();
				callPayNS(intent,ThirdTransType.TRANS_SCAN_PAY);
			}else{
				callPayNS(new Intent(),ThirdTransType.TRANS_NULL);
			}
		}

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_MICROPAY_NS)){
			mPayType = Constant.PAY_TYPE_MICROPAY_NS;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			if(!StringUtil.isEmpty(totalMoney)){
				Intent intent = initIntent();
				callPayNS(intent,ThirdTransType.TRANS_SCAN_PAY);
			}else{
				callPayNS(new Intent(),ThirdTransType.TRANS_NULL);
			}
		}

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_BANKCARD_NS)){
			bankPayType = Constant.BANKPAYTYPE_NONGSHAN;
			mPayType = Constant.PAY_TYPE_BANKCARD_NS;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			consume_ns();
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_BANKCANCEL_NS)){
			mPayType = Constant.PAY_TYPE_BANKCARD_NS;
			mOpType = Constant.KEYBOARD_OP_TYPE_RETURN;
			consumeCancel_ns();
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_SETTING_NS)){
			mApplication.getOperator().setBankType(Constant.BANKPAYTYPE_NONGSHAN);
			settings();
		}

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_PREAUTH_NS)){
			mApplication.getOperator().setBankType(Constant.BANKPAYTYPE_NONGSHAN);
			preauth();
		}
	}
	//刷卡消费
	public void consume_ns() {
		if(!StringUtil.isEmpty(totalMoney)){
			Intent intent = initIntent();
			callPayNS(intent, 2);
		}else {
			showKeyboard(Constant.GREQUEST_CODE_CARDPAY, false);
		}
	}
	//刷卡消费撤销
	public void consumeCancel_ns() {
		// 输入原交易流水号
		final EditText et = new EditText(this);
		new AlertDialog.Builder(this).setTitle("请输入原交易流水号")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setView(et)
				.setPositiveButton("确定", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String input = et.getText().toString();
						if ("".equals(input)) {
							Toast.makeText(mContext, "原交易流水号不能为空！", Toast.LENGTH_LONG).show();
						}
						else {
							Intent intent = new Intent();
							intent.putExtra("oriVoucherNo", input);
							callPayNS(intent, 7);
						}
					}
				})
				.setNegativeButton("取消", null)
				.show();
	}

	private void callPayNS(Intent intent, int transType) {
		if(transType == ThirdTransType.TRANS_NULL){
			showKeyboard(Constant.GREQUEST_CODE_SCANNIN_NS, false);
		}else{
			intent.setClassName("com.newland.nxs", "com.newland.payment.ui.activity.MainActivity");
			intent.putExtra("transType", transType);
			startActivityForResult(intent,Integer.valueOf("200"+transType));
		}
	}

	//====================农商支付==========================================
// ====================其他支付==========================================
	private void other(Payway payway){
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_CASH)){
			mPayType = Constant.PAY_TYPE_CASH;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			cash();
		}

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_YIPAY)){
			mPayType = Constant.PAY_TYPE_YIPAY;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			yipay();
		}

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_FEIXIPAY)){
			mPayType = Constant.PAY_TYPE_FEIXIPAY;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			mAmount = "0";
			showScanCode();
		}

		if(payway.getPaywaynum().equals(Constant.PAY_WAY_SCANCODE)){
			ToastUtil.showToast(mContext, "正在开发中！", ToastUtil.WARNING);
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_BAIDU)){
			ToastUtil.showToast(mContext, "正在开发中！", ToastUtil.WARNING);
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_QQ)){
			ToastUtil.showToast(mContext, "正在开发中！", ToastUtil.WARNING);
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_JD)){
			ToastUtil.showToast(mContext, "正在开发中！", ToastUtil.WARNING);
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_YF)){
			ToastUtil.showToast(mContext, "正在开发中！", ToastUtil.WARNING);
		}
	}
	//翼支付
	public void yipay() {
		if(!StringUtil.isEmpty(totalMoney)){
			initIntent();
			showScanCode();
		}else{
			showKeyboard(Constant.GREQUEST_CODE_KEYBOARD, true); // 键盘输入
		}
	}
	public void cash(){
		if(!StringUtil.isEmpty(totalMoney)){
			initIntent();
			if(StringUtil.isEmpty(orderNum)&&"1".equals(isFromType)){
				Toast.makeText(mContext, "订单号不存在！", Toast.LENGTH_LONG).show();
				return;
			}else if(StringUtil.isEmpty(orderNum)){
				orderNum =  StringUtil.getSeq().toString();
			}
			PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
			task.execute(orderNum);
		}else {
			showKeyboard(Constant.GREQUEST_CODE_CASH, false);
		}
	}
	// ====================其他支付==========================================
// ====================联惠支付==========================================
	private void lianhui(Payway payway){
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_ALIPAY_LH)){
			mPayType = Constant.PAY_TYPE_ALIPAY_LH;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			pay_2();
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_MICROPAY_LH)){
			mPayType = Constant.PAY_TYPE_MICROPAY_LH;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			pay_2();
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_HB)){
			mPayType = Constant.PAY_TYPE_HB_LH;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			pay_2();
		}
	}

// ====================联惠支付==========================================

	// ====================威富通支付==========================================
	private void wft(Payway payway){
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_ALIPAY_WF)){
			mPayType = Constant.PAY_TYPE_ALIPAY_WF;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			pay_2();
		}
		if(payway.getPaywaynum().equals(Constant.PAY_WAY_MICROPAY_WF)){
			mPayType = Constant.PAY_TYPE_MICROPAY_WF;
			mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
			pay_2();
		}
	}
	// ====================威富通支付==========================================

	// 管理
	public void settings() {
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, CardAdminActivity.class);
		startActivity(intent);
	}

	/**
	 * 键盘输入
	 */
	private void showKeyboard(int requestCode, boolean isReturn) {
		Intent intent = new Intent();
		intent.putExtra(Constant.PARAM_ISRETURN, isReturn);
		if(!StringUtil.isEmpty(totalMoney)){
			intent.putExtra("totalMoney",totalMoney);
		}
		intent.setClass(MainActivity.this, KeyboardActivity.class);
		startActivityForResult(intent, requestCode);
	}

	/**
	 * 扫描条码
	 */
	private void showScanCode() {
		Intent intent = new Intent();
		intent.putExtra(Constant.PARAM_OPTYPE, mOpType);
		intent.putExtra(Constant.PARAM_AMOUNT, mAmount);
		intent.putExtra(Constant.PARAM_SUMMARY, mSummary);
		intent.putExtra(Constant.PARAM_PAYTYPE, mPayType);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);  // 无动画
		if(	mPayType == Constant.PAY_TYPE_YIPAY){
			intent.setClass(MainActivity.this, YimaScanActivity.class);
		}else if(mPayType == Constant.PAY_TYPE_FEIXIPAY){
			intent.setClass(MainActivity.this, FeixiScanT2Activity.class);
		}else{
			intent.setClass(MainActivity.this, ScanCodeActivity.class);
		}
		startActivityForResult(intent, Constant.GREQUEST_CODE_SCANNIN);
		overridePendingTransition(R.anim.empty,R.anim.empty);
	}

	/**
	 * 返回结果处理
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			switch (requestCode) {
				case Constant.GREQUEST_CODE_KEYBOARD: // 键盘金额输入--扫描
					if (resultCode == RESULT_OK) {
						mOpType = data.getIntExtra(Constant.PARAM_OPTYPE, Constant.KEYBOARD_OP_TYPE_PAY);
						mAmount = data.getStringExtra(Constant.PARAM_AMOUNT);
						mSummary = data.getStringExtra(Constant.PARAM_SUMMARY);
						// 扫描
						showScanCode();
					} else {

					}
					break;
				case Constant.GREQUEST_CODE_SCANNIN: // 扫描后返回--服务端支付
					if (resultCode == RESULT_OK) {
						scanCode = data.getStringExtra(Constant.PARAM_SCANCODE);
						if (mPayType == Constant.PAY_TYPE_MICROPAY_YS
								&& mOpType == Constant.KEYBOARD_OP_TYPE_RETURN) {
							Intent intent = new Intent();
							intent.putExtra("traceNo",scanCode);
							callPay(intent, 2010);
							// 银盛支付宝扫码退货
						}else if (mPayType == Constant.PAY_TYPE_ALIPAY_YS
								&& mOpType == Constant.KEYBOARD_OP_TYPE_RETURN) {
							Intent intent = new Intent();
							intent.putExtra("traceNo",scanCode);
							callPay(intent, 2011);
						} else if (mPayType == Constant.PAY_TYPE_BANKUNION_YS
								&& mOpType == Constant.KEYBOARD_OP_TYPE_RETURN) {
							Intent intent = new Intent();
							intent.putExtra("traceNo",scanCode);
							callPay(intent, 1018);
						} else{
							// 支付
							PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
							task.execute(scanCode);
						}
					}
					break;
				case Constant.GREQUEST_CODE_SCANNIN_NS: // 农商输入金额返回
					if (resultCode == RESULT_OK) {
						mOpType = data.getIntExtra(Constant.PARAM_OPTYPE, Constant.KEYBOARD_OP_TYPE_PAY);
						mAmount = data.getStringExtra(Constant.PARAM_AMOUNT);
						mSummary = data.getStringExtra(Constant.PARAM_SUMMARY);
						// 农商扫码退货
						if ((mPayType == Constant.PAY_TYPE_MICROPAY_NS
								|| mPayType == Constant.PAY_TYPE_ALIPAY_NS)
								&& mOpType == Constant.KEYBOARD_OP_TYPE_RETURN) {
							Intent intent = new Intent();
							callPayNS(intent, ThirdTransType.TRANS_SCAN_REFUND);
						} else {
							scanMoney = data.getStringExtra(Constant.PARAM_SUMMARY);
							Intent intent = new Intent();
							intent.putExtra("amount", Long.parseLong(scanMoney));// 金额统一以分为单位,long类型 Long.parseLong(StringUtil.changeY2F(amount)));
							callPayNS(intent, ThirdTransType.TRANS_SCAN_PAY);
						}
					}
					break;
				case Constant.GREQUEST_CODE_SCANNIN_YS: // 银盛输入金额返回
					if (resultCode == RESULT_OK) {
						mOpType = data.getIntExtra(Constant.PARAM_OPTYPE, Constant.KEYBOARD_OP_TYPE_PAY);
						mAmount = data.getStringExtra(Constant.PARAM_AMOUNT);
						mSummary = data.getStringExtra(Constant.PARAM_SUMMARY);
						if (mOpType == Constant.KEYBOARD_OP_TYPE_RETURN) {
							// 扫描退货
							showScanCode();
						} else {
							Intent intent = new Intent();
							intent.putExtra("amount", Long.parseLong(mSummary));// 金额统一以分为单位,long类型 Long.parseLong(StringUtil.changeY2F(amount)));
							if (mPayType == Constant.PAY_TYPE_MICROPAY_YS) {
								callPay(intent, 2004);
							}
							if (mPayType == Constant.PAY_TYPE_ALIPAY_YS) {
								callPay(intent, 2006);
							}
							if(mPayType == Constant.PAY_TYPE_BANKUNION_YS){
								callPay(intent, 1016);
							}
						}
					}
					break;
				case Constant.GREQUEST_CODE_CARDPAY: // 键盘输入返回---银盛刷卡消费
					if (resultCode == RESULT_OK) {
						String amount = data.getStringExtra(Constant.PARAM_SUMMARY);
						Intent intent = new Intent();
						orderId = StringUtil.genseq();
						//入库
						insertDB(amount);
						intent.putExtra("orderId", orderId);
						intent.putExtra("amount", Long.parseLong(amount));// 金额统一以分为单位,long类型 Long.parseLong(StringUtil.changeY2F(amount)));
						if (Constant.BANKPAYTYPE_NONGSHAN.equals(bankPayType)) {
							callPayNS(intent, 2);
						} else if (Constant.BANKPAYTYPE_YINGSHEN.equals(bankPayType)) {
							log.info(" 刷卡消费:" + amount + " ");
							//秒到
							if( Constant.PAY_TYPE_BANKCARD_Q == mPayType){
								callPay(intent, 1009);
							}else{
								callPay(intent, 101);
							}

						} else {
							Toast.makeText(mContext, "刷卡通道未设置！", Toast.LENGTH_LONG).show();
						}
					} else {

					}
					break;
				case Constant.GREQUEST_CODE_CASH: // 现金消费
					if (resultCode == RESULT_OK) {
						totalMoney = data.getStringExtra(Constant.PARAM_SUMMARY);
						if (StringUtil.isEmpty(totalMoney)) {
							totalMoney = "0";
						}
						cash();
					} else {
						Toast.makeText(mContext, "现金支付失败！", Toast.LENGTH_LONG).show();
					}
					break;
				case 100101: // 刷卡消费返回结果（银盛）
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！100101", Toast.LENGTH_LONG).show();
						log.info(" 返回空数据");
						return;
					}
					//有返回清除数据
					RecordDB rdb = new RecordDB();
					rdb.deleteByOrderid(orderId);

					log.info(" 刷卡返回成功 ");
					int transResult = data.getIntExtra("transResult", -1); // 交易状态码：0成功；-1失败
					Long amount =data.getLongExtra("amount", 0l);    // 金额
					String pan = data.getStringExtra("pan");    // 卡号
					String bankCardType = data.getStringExtra("bankCardType");    //借贷记标识
					if (pan == null) pan = "";
					if (bankCardType == null) bankCardType = "";
					if (amount != null) {
						mSummary = amount.toString();
					}
					if (transResult == 0) {
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType);
						invoice();
					} else {
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType, "2", transResult + "",orderId);
					}
					log.info(" 刷卡返回数据 "+transResult+" " + amount + " " + pan + " " + bankCardType);
					break;
				case 1001009: // 刷卡秒到消费返回结果（银盛）
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！1001009", Toast.LENGTH_LONG).show();
						log.info(" 返回空数据");
						return;
					}
					//有返回清除数据
					rdb = new RecordDB();
					rdb.deleteByOrderid(orderId);

					amount = data.getLongExtra("amount", 0l);    // 金额
					pan = data.getStringExtra("pan");    // 卡号
					bankCardType = data.getStringExtra("bankCardType");    //借贷记标识
					if (amount != null) {
						mSummary = amount.toString();
					}
					if (pan == null) pan = "";
					if (bankCardType == null) bankCardType = "";

					log.info(" 刷卡秒到返回成功 ");
					transResult = data.getIntExtra("transResult", -1); // 交易状态码：0成功；-1失败

					if (transResult == 0) {
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType);
						invoice();
					} else {
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType, "2", transResult + "",orderId);
					}
					log.info(" 刷卡秒到返回数据 "+transResult+" " + amount + " " + pan + " " + bankCardType);
					break;
				case 1001022: // 查询订单返回（银盛）
					orderId = orderMap.get(orderix+"");
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！1001022", Toast.LENGTH_LONG).show();
						return;
					}
					transResult = data.getIntExtra("transResult", -1); // 交易状态码：0成功；-1失败
					if (transResult == 0) {
						amount = data.getLongExtra("amount", 0l);    // 金额
						pan = data.getStringExtra("pan");    // 卡号
						bankCardType = data.getStringExtra("bankCardType");    //借贷记标识
						if (amount != null) {
							mSummary = amount.toString();
						}
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType);
					}
					rdb = new RecordDB();
					rdb.deleteByOrderid(orderId);
					orderix++;
					if(orderix>orderMap.size()){
						orderMap.clear();
					}
					break;
				case 100106: // 刷卡消费撤销返回结果（银盛）
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！100106", Toast.LENGTH_LONG).show();
						return;
					}
					transResult = data.getIntExtra("transResult", -1); // 交易状态码：0成功；-1失败
					if (transResult == 0) {
						// 保存交易记录
						pan = data.getStringExtra("pan");    // 卡号
						amount = data.getLongExtra("amount", 0l);    // 金额
						bankCardType = data.getStringExtra("bankCardType");    //借贷记标识
						mSummary = amount.toString();
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType);
					}
					break;
				case 1002004: // 微信（银盛）
				case 1002006: // 支付宝（银盛）
				case 1001016: // 银联（银盛）
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！1002004|1002006|1001016", Toast.LENGTH_LONG).show();
						return;
					}
					transResult = data.getIntExtra("transResult", -1); // 交易状态码：0成功；-1失败
					if (transResult == 0) {
						// 保存交易记录
						amount = data.getLongExtra("amount", 0l);    // 金额
						String traceNo = data.getStringExtra("traceNo");    // 流水号
						mSummary = amount.toString();
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(traceNo);
						// 闪电开票
						invoice();
					}
					break;
				case 1002010: // 微信退款（银盛）
				case 1002011: // 支付宝退款（银盛）
				case 1001018: // 银联退款（银盛）
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！1002010｜1002011|1001018", Toast.LENGTH_LONG).show();
						return;
					}
					transResult = data.getIntExtra("transResult", -1); // 交易状态码：0成功；-1失败
					if (transResult == 0) {
						// 保存交易记录
						amount = data.getLongExtra("amount", 0l);    // 金额
						String traceNo = data.getStringExtra("traceNo");    // 流水号
						mSummary = amount.toString();
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(traceNo);

						// 闪电开票
						invoice();
					}
					break;
				case 2002: // 刷卡消费返回结果（农商）
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！2002", Toast.LENGTH_LONG).show();
						return;
					}
					String responseCode = data.getStringExtra("responseCode"); // 交易状态码：00成功；其他失败
					if ("00".equals(responseCode)) {
						// 保存交易记录
						amount = data.getLongExtra("amount", 0l);    // 金额
						pan = data.getStringExtra("cardNo");    // 卡号
						bankCardType = data.getStringExtra("bankCardType");    //借贷记标识
						mSummary = amount.toString();
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType);

						// 闪电开票
						invoice();
					}
					break;
				case 2007: // 刷卡消费撤销返回结果（农商）
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！2007", Toast.LENGTH_LONG).show();
						return;
					}
					responseCode = data.getStringExtra("responseCode"); // 交易状态码：00成功；其他失败
					if ("00".equals(responseCode)) {
						// 保存交易记录
						pan = data.getStringExtra("cardNo");    // 卡号
						amount = data.getLongExtra("transAmount", 0l);    // 金额
						bankCardType = data.getStringExtra("bankCardType");    //借贷记标识
						mSummary = amount.toString();
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(pan, bankCardType);
					}
					break;
				case 2002001: // 扫描支付（农商）
				case 2002002: // 扫描退货（农商）
					if (data == null) {
						Toast.makeText(mContext, "返回空类型！20066|20067", Toast.LENGTH_LONG).show();
						return;
					}
					responseCode = data.getStringExtra("responseCode"); // 交易状态码：00成功；其他失败
					if ("00".equals(responseCode)) {
						String scanCode = data.getStringExtra(Constant.PARAM_SCANCODE);
						amount = data.getLongExtra("amount", 0l);    // 金额
						String channelId = data.getStringExtra("channelId");
						if ("alipay".equals(channelId)) {
							mPayType = Constant.PAY_TYPE_ALIPAY_NS;
						}
						if ("wxpay".equals(channelId)) {
							mPayType = Constant.PAY_TYPE_MICROPAY_NS;
						}
						mSummary = amount.toString();
						// 支付
						PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
						task.execute(scanCode);

						invoice();
					} else {
						Toast.makeText(mContext, "支付失败:" + responseCode, Toast.LENGTH_LONG).show();
					}
					break;
				default:
					log.info(" 返回无效类型　" + requestCode + " " + resultCode);
					break;
			}
		}catch(Exception ex){
			log.info(" 返回异常　" + requestCode + " " + resultCode+" ",ex);
		}
	}

	private void initBankDB(){
		mOpType =  Constant.KEYBOARD_OP_TYPE_PAY;
		mPayType = Constant.PAY_TYPE_BANKCARD;
		try {
			RecordDB rdb = new RecordDB();
			List<RecordModel> recordModels = rdb.dbFind();
			if(recordModels==null){
				return;
			}
			int i = 0;
			log.info(" 同步订单： "+recordModels.size());
			for (RecordModel recordModel : recordModels) {
				Intent intent = new Intent();
				orderId = recordModel.getOrderid();
				orderMap.put(""+i,orderId);
				intent.putExtra("oldOrderId", orderId); // 订单号
				callPay(intent, 1022);
				i++;
			}
		}catch (Exception ex){
			ex.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(CloudPayApplication.from==1){
			CloudPayApplication.from=0;
			finish();
			return;
		}
	}
}